
//
//  ComposeViewController.swift
//  Sina
//
//  Created by YYY on 2017/9/1.
//  Copyright © 2017年 成品家（北京）网路科技有限公司. All rights reserved.
//

import UIKit

import SVProgressHUD

class ComposeViewController: UIViewController {

    //文本编辑视图
    @IBOutlet weak var textView: CPJComposeTextView!
    
    //文本视图
    @IBOutlet weak var textInputView: UITextView!
    
    lazy var emoticonView: EmoticonInputView = EmoticonInputView.emoticonView { [weak self] (emoticonModel) in
        
        self?.textView.insertEmoticonModel(model: emoticonModel)
    }

    
    //工具栏
    @IBOutlet weak var toolBar: UIToolbar!
    
    //发布按钮
    @IBOutlet var sendButton: UIButton!
    
    //标题文本 属性文本换行热键：option + 回车
    //逐行选中文本，设置文本属性
    //添加行间距，增加空行，设置空行字体大小
    @IBOutlet var titleLabel: UILabel!
    
    //工具栏底部约束
    @IBOutlet weak var toolbarBottomCons: NSLayoutConstraint!
    
//    //懒加载发送按钮
//    lazy var sendButton: UIButton = {
//        let btn = UIButton()
//        btn.frame = CGRect(x: 0, y: 0, width: 45, height: 35)
//        btn.setTitle("发送", for: .normal)
//        btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
//        btn.setTitleColor(UIColor.white, for: .normal)
//        btn.setTitleColor(UIColor.gray, for: .disabled)
//        
//        btn.setBackgroundImage(UIImage(named: "common_button_orange"), for: .normal)
//        btn.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), for: .highlighted)
//        btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), for: .disabled)
//        
//        return btn
//    }()
    
    //MARK：- 视图生命周期
    override func viewDidLoad() {
        super.viewDidLoad()

        //初始化界面
        setupUI()
       
        //注册监听者 监听键盘通知
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardChange), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        

        // Do any additional setup after loading the view.
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        //激活键盘
        textView.becomeFirstResponder()
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        //隐藏键盘
        textView.resignFirstResponder()
    }
    //监听键盘变化
    @objc private func keyboardChange(notification: Notification)
    {
        //目标rect
        let cgrect = ((notification.userInfo?["UIKeyboardFrameEndUserInfoKey"]) as? NSValue)?.cgRectValue
        
        guard let rect = cgrect,
        let duration = ((notification.userInfo?["UIKeyboardAnimationDurationUserInfoKey"]) as? NSNumber)?.doubleValue else
        {
            return
        }
        
        //设置底部约束高度
        let offsetBottom = view.bounds.height - rect.origin.y
        //更新底部约束
        toolbarBottomCons.constant = offsetBottom
        
        //动画更新底部约束
        UIView.animate(withDuration: duration) { 
            self.view.layoutIfNeeded()
        }

    }
    
    //移除通知
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    @IBAction func sendWeibo()
    {
        print("发布微博")
        guard let text = textView.emoticonText else
        {
            return
        }
        let image = UIImage(named: "avatar_default_big")
        
        CPJNetworkManager.shared.postWeibo(text: text,image: image) { (jsonDict, isSuccess) in
            //print(jsonDict)
            
            let message = isSuccess ? "发布成功" : "网络不给力"
            
            //修改指示器样式
            SVProgressHUD.setDefaultStyle(.dark)
            
            //显示提示
            SVProgressHUD.show(withStatus: message)
            
            //如果成功，延迟一段时间，关闭当前窗口
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1)
            {
                //恢复样式
                SVProgressHUD.setDefaultStyle(.light)
                //关闭
                self.close()
                
                SVProgressHUD.dismiss()
            }
        }
    }
    @objc fileprivate func close()
    {
        dismiss(animated: true, completion: nil)
    }
    
    //表情键盘
    @objc fileprivate func emoticonKeyboard()
    {
        //文本框的输入视图
        //let view = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 258))
        
        //设置文本框键盘视图
        textView.inputView = (textView.inputView == nil) ? emoticonView : nil
        
        //刷新键盘视图（切换键盘必须要刷新输入视图）
        textView.reloadInputViews()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

private extension ComposeViewController
{
    //初始化界面
    func setupUI()
    {

        
        view.backgroundColor = UIColor.white
        //设置导航栏
        setupNavigationBar()
        //设置工具栏
        setupToolBar()
    }
    
    //设置导航栏
    func setupNavigationBar()
    {
        navigationItem.leftBarButtonItem = UIBarButtonItem(size: CGSize(width: 50, height: 30), titleStr: "关闭", fontSize: 14, target: self, selector: #selector(close), isBack: false)
        
        //设置导航栏右按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendButton)
        
        //标题视图
        navigationItem.titleView = titleLabel
        //sendButton.isEnabled = false
    }
    
    //设置工具栏
    func setupToolBar()
    {
        let itemPictureArray = [["imageName": "compose_toolbar_picture"],
                                ["imageName": "compose_mentionbutton_background"],
                                ["imageName": "compose_trendbutton_background"],
                                ["imageName": "compose_emoticonbutton_background", "actionName": "emoticonKeyboard"],
                                ["imageName": "compose_add_background"]
        ]
        
        var itemsButtonArray = [UIBarButtonItem]()
        
        for itemDict in itemPictureArray
        {
            guard let imageName = itemDict["imageName"] else
            {
                continue
            }
            
            let imageNormal = UIImage(named: imageName)
            let imageHighlighted = UIImage(named: imageName + "_highlighted")
            let itemButton = UIButton()
            //普通状态
            itemButton.setImage(imageNormal, for: .normal)
            //高亮状态
            itemButton.setImage(imageHighlighted, for: .highlighted)
            itemButton.sizeToFit()
            
            if let actionName = itemDict["actionName"]
            {
                //控制表情键盘
                itemButton.addTarget(self, action: Selector(actionName), for: .touchUpInside)
            }
            itemsButtonArray.append(UIBarButtonItem(customView: itemButton))
            //添加弹簧间距
            itemsButtonArray.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
        }
        //移除最后一个弹簧
        itemsButtonArray.removeLast()
        //设置工具栏的items
        toolBar.items = itemsButtonArray
    }
}

/*
 通知：一对多
 代理：一对一
 */
// MARK：UITextViewDelegate
extension ComposeViewController: UITextViewDelegate
{
    func textViewDidChange(_ textView: UITextView) {
        sendButton.isEnabled = textView.hasText
    }
}
